package nciae.db.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import nciae.db.common.CommonResult;
import nciae.db.pojo.entity.Project;
import nciae.db.pojo.entity.User;
import nciae.db.pojo.vo.*;
import nciae.db.service.ExportService;
import nciae.db.service.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
public class ProjectController {

    @Autowired
    private ProjectService projectService;

    @Autowired
    private ExportService exportService;

    @GetMapping("/project/exportWord/{id}")
    public void exportWord(@PathVariable("id") Long id, HttpServletResponse response) {
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment;filename=SurveyReport.docx");
        try {
            exportService.generateSurveyWord(id, response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("导出Word失败", e);
        }
    }

    @GetMapping("/project/exportPdf/{id}")
    public void exportPdf(@PathVariable("id") Long id, HttpServletResponse response) {
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment;filename=SurveyReport.pdf");
        try {
            exportService.generateSurveyPdf(id, response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("导出PDF失败", e);
        }
    }

    @GetMapping("/project/scheme_exportWord/{id}")
    public void scheme_exportWord(@PathVariable("id") Long id, HttpServletResponse response) {
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment;filename=SurveyReport.docx");
        try {
            exportService.generateSchemeWord(id, response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("导出Word失败", e);
        }
    }

    @GetMapping("/project/scheme_exportPdf/{id}")
    public void scheme_exportPdf(@PathVariable("id") Long id, HttpServletResponse response) {
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment;filename=SurveyReport.pdf");
        try {
            exportService.generateSchemePdf(id, response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("导出PDF失败", e);
        }
    }

    @GetMapping("/project/report_exportWord/{id}")
    public void report_exportWord(@PathVariable("id") Long id, HttpServletResponse response) {
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment;filename=SurveyReport.docx");
        try {
            exportService.generateReportWord(id, response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("导出Word失败", e);
        }
    }

    @GetMapping("/project/report_exportPdf/{id}")
    public void report_exportPdf(@PathVariable("id") Long id, HttpServletResponse response) {
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment;filename=SurveyReport.pdf");
        try {
            exportService.generateReportPdf(id, response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("导出PDF失败", e);
        }
    }

    @ResponseBody
    @GetMapping("/project/listProjectName")
    public CommonResult<List<String>> listProjectName() {
        return projectService.listProjectName();
    }

    @GetMapping("/project/index")
    public ModelAndView index(){
        List<Project> projects = projectService.getAllProjects(); // Ensure this method exists
        ModelAndView view = new ModelAndView("project/index");
        view.addObject("projects", projects);
        return view;
    }

    @GetMapping("/pretraining/index")
    public ModelAndView pretraining_index(){
        List<Project> projects = projectService.getAllProjects(); // Ensure this method exists
        ModelAndView view = new ModelAndView("pretraining/index");
        view.addObject("projects", projects);
        return view;
    }

    @GetMapping("/project/form")
    public ModelAndView form(Integer id){
        Project project;
        if(id == 0){
            project = new Project();
            project.setId(0);
            // Initialize other fields to prevent nulls
            project.setProjectName("");
            project.setBeginDate(new java.util.Date());
            project.setEndDate(new java.util.Date());
            project.setNum(0);
            project.setSubject("");
            project.setState(0);
        } else {
            project = projectService.getProjectInfo(id);
            if(project == null){
                return new ModelAndView("error/404");
            }
        }
        ModelAndView view = new ModelAndView("project/form");
        view.addObject("model", project);
        return view;
    }

    @GetMapping("/project/doc_reportForm")
    public ModelAndView doc_reportForm(@RequestParam(value = "id") Integer Projectid, HttpSession session){
        DocReportVO docReportVO = new DocReportVO();
        docReportVO = projectService.getdocReportInfo(Projectid,session);
        if(docReportVO == null){
            return new ModelAndView("error/404");
        }
        ModelAndView view = new ModelAndView("pretraining/doc_reportForm");
        view.addObject("model", docReportVO);
        return view;
    }

    @GetMapping("/project/doc_schemeForm")
    public ModelAndView doc_schemeForm(@RequestParam(value = "id") Integer ProjectId, HttpSession session){
        DocSchemeVO docSchemeVO = new DocSchemeVO();
        docSchemeVO = projectService.getdocSchemeInfo(ProjectId, session);
        if(docSchemeVO == null){
            return new ModelAndView("error/404");
        }
        ModelAndView view = new ModelAndView("pretraining/doc_schemeForm");
        view.addObject("model", docSchemeVO);
        return view;
    }

    @GetMapping("/project/version_infoForm")
    public ModelAndView version_infoForm(@RequestParam(value = "id") Integer ProjectId, HttpSession session) throws JsonProcessingException {
        List<DefaultVersionInfoVO> defaultVersionInfoVOs = projectService.getVersionInfoDefault(ProjectId, session);
        if (defaultVersionInfoVOs == null) {
            defaultVersionInfoVOs = new ArrayList<>();  // 确保为空时是空数组
        }
        // 将列表转换为 JSON 字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String surveyVersionInfoJson = objectMapper.writeValueAsString(defaultVersionInfoVOs);
        ModelAndView view = new ModelAndView("pretraining/versionInfoForm");
        view.addObject("SurveyVersionInfo", defaultVersionInfoVOs);
        view.addObject("surveyVersionInfoJson", surveyVersionInfoJson);
        return view;
    }

    @GetMapping("/project/doc_surveyForm")
    public ModelAndView doc_surveyForm(@RequestParam(value = "id") Integer ProjectId, HttpSession session){
        DocSurveyVO docSurveyVO = new DocSurveyVO();
        docSurveyVO = projectService.getdocsurveyInfo(ProjectId, session);
        if(docSurveyVO == null){
            return new ModelAndView("error/404");
        }
        ModelAndView view = new ModelAndView("pretraining/doc_surveyForm");
        view.addObject("model", docSurveyVO);
        return view;
    }



    @ResponseBody
    @RequestMapping("/project/list")
    public CommonResult<List<Project>> list(@RequestParam(value = "page", defaultValue = "1") Integer page, @RequestParam(value = "limit", defaultValue = "50") Integer limit,String projectName,
                                            @RequestParam(value = "beginDate",defaultValue = "2000-1-1") Date beginDate,
                                            @RequestParam(value = "endDate",defaultValue = "3000-1-1") Date endDate, Integer state){

        CommonResult<List<Project>> rs = projectService.search(projectName, state,  beginDate, endDate, page, limit);
        return rs;
    }

    /**\
     * 查询所有的项目
     * @return
     */
    @ResponseBody
    @GetMapping("/project/lists")
    public CommonResult<List<Project>> listProject() {
        //CommonResult<List<Project>> result = new CommonResult<List<Project>>();
        CommonResult<List<Project>> result=projectService.list();
        return result;
    }
    @PostMapping("/project/save")
    @ResponseBody
    public CommonResult save(@RequestBody Project project){
        CommonResult<Project> result = projectService.save(project);
        return result;
    }

    @ResponseBody
    @PostMapping("/project/del")
    public CommonResult<Boolean> del(Integer id){
        return projectService.delete(id);
    }

    @ResponseBody
    @PostMapping("/project/saveDoc_Report")
    public CommonResult<Boolean> saveDoc_Report(@RequestBody DocReportVO docReportVO, HttpSession session){
        CommonResult<Boolean> result = new CommonResult<>();
        User currentUser = (User)session.getAttribute("user");
        if("管理员".equals(currentUser.getRole())){
            String advice = docReportVO.getAdvice();
            if(advice == null || StringUtils.isBlank(advice)){
                result.setCode(-1);
                result.setMsg("请填写审批意见");
                result.setData(false);
                return result;
            }
        }else{
            String projectName = docReportVO.getProjectName();
            if(projectName == null || StringUtils.isBlank(projectName)){
                result.setCode(-1);
                result.setMsg("项目名称不能为空");
                result.setData(false);
                return result;
            }
            String department = docReportVO.getDepartment();
            if(department == null || StringUtils.isBlank(department)){
                result.setCode(-1);
                result.setMsg("二级单位不能为空");
                result.setData(false);
                return result;
            }
            String background = docReportVO.getBackground();
            if(background == null || StringUtils.isBlank(background)){
                result.setCode(-1);
                result.setMsg("诊断背景不能为空");
                result.setData(false);
                return result;
            }
            String target = docReportVO.getTarget();
            if(target == null || StringUtils.isBlank(target)){
                result.setCode(-1);
                result.setMsg("诊断目的不能为空");
                result.setData(false);
                return result;
            }
            String res = docReportVO.getResult();
            if(res == null || StringUtils.isBlank(res)){
                result.setCode(-1);
                result.setMsg("调研诊断分析结果不能为空");
                result.setData(false);
                return result;
            }
            String suggest = docReportVO.getSuggest();
            if(suggest == null || StringUtils.isBlank(suggest)){
                result.setCode(-1);
                result.setMsg("思考与建议不能为空");
                result.setData(false);
                return result;
            }
        }

        return projectService.saveDoc_Report(docReportVO, session);
    }

    @ResponseBody
    @PostMapping("/project/saveDoc_Scheme")
    public CommonResult<Boolean> saveDoc_Scheme(@RequestBody DocSchemeVO docSchemeVO, HttpSession session){
        CommonResult<Boolean> result = new CommonResult<>();
        User currentUser = (User)session.getAttribute("user");
        if("管理员".equals(currentUser.getRole())){
            String advice = docSchemeVO.getAdvice();
            if(advice == null || StringUtils.isBlank(advice)){
                result.setCode(-1);
                result.setMsg("请填写审批意见");
                result.setData(false);
                return result;
            }
        }
        else{
            String projectName = docSchemeVO.getProjectName();
            if(projectName == null || StringUtils.isBlank(projectName)){
                result.setCode(-1);
                result.setMsg("项目名称不能为空");
                result.setData(false);
                return result;
            }
            String department = docSchemeVO.getDepartment();
            if(department == null || StringUtils.isBlank(department)){
                result.setCode(-1);
                result.setMsg("二级单位不能为空");
                result.setData(false);
                return result;
            }
            String background = docSchemeVO.getBackground();
            if(background == null || StringUtils.isBlank(background)){
                result.setCode(-1);
                result.setMsg("诊断背景不能为空");
                result.setData(false);
                return result;
            }
            String target = docSchemeVO.getTarget();
            if(target == null || StringUtils.isBlank(target)){
                result.setCode(-1);
                result.setMsg("诊断目的不能为空");
                result.setData(false);
                return result;
            }
            String object = docSchemeVO.getObject();
            if(object == null || StringUtils.isBlank(object)){
                result.setCode(-1);
                result.setMsg("诊断区域与对象不能为空");
                result.setData(false);
                return result;
            }
            String content = docSchemeVO.getContent();
            if(content == null || StringUtils.isBlank(content)){
                result.setCode(-1);
                result.setMsg("诊断内容不能为空");
                result.setData(false);
                return result;
            }
            String method = docSchemeVO.getMethod();
            if(method == null || StringUtils.isBlank(method)){
                result.setCode(-1);
                result.setMsg("诊断方法不能为空");
                result.setData(false);
                return result;
            }
            String flow = docSchemeVO.getFlow();
            if(flow == null || StringUtils.isBlank(flow)){
                result.setCode(-1);
                result.setMsg("诊断流程不能为空");
                result.setData(false);
                return result;
            }
            String res = docSchemeVO.getResult();
            if(res == null || StringUtils.isBlank(res)){
                result.setCode(-1);
                result.setMsg("预期诊断成果不能为空");
                result.setData(false);
                return result;
            }
            String person = docSchemeVO.getPerson();
            if(person == null || StringUtils.isBlank(person)){
                result.setCode(-1);
                result.setMsg("人员组织分工不能为空");
                result.setData(false);
                return result;
            }
            String schedule = docSchemeVO.getSchedule();
            if(schedule == null || StringUtils.isBlank(schedule)){
                result.setCode(-1);
                result.setMsg("日程安排不能为空");
                result.setData(false);
                return result;
            }

        }
        return projectService.saveDoc_Scheme(docSchemeVO, session);
    }

    @ResponseBody
    @PostMapping("/project/saveDoc_Survey")
    public CommonResult<Boolean> saveDoc_Survey(@RequestBody DocSurveyVO docSurveyVO, HttpSession session){
        CommonResult<Boolean> result = new CommonResult<>();
        User currentUser = (User)session.getAttribute("user");
        if("管理员".equals(currentUser.getRole())){
            String advice = docSurveyVO.getAdvice();
            if(advice == null || StringUtils.isBlank(advice)){
                result.setCode(-1);
                result.setMsg("请填写审批意见");
                result.setData(false);
                return result;
            }
        }else{
            String projectName = docSurveyVO.getProjectName();
            if(projectName == null || StringUtils.isBlank(projectName)){
                result.setCode(-1);
                result.setMsg("项目名称不能为空");
                result.setData(false);
                return result;
            }
            String department = docSurveyVO.getDepartment();
            if(department == null || StringUtils.isBlank(department)){
                result.setCode(-1);
                result.setMsg("二级单位不能为空");
                result.setData(false);
                return result;
            }
            Integer docType = docSurveyVO.getDocType();
            if(docType == null){
                result.setCode(-1);
                result.setMsg("请选择诊断方式");
                result.setData(false);
                return result;
            }
            String content = docSurveyVO.getContent();
            if(content == null || StringUtils.isBlank(content)){
                result.setCode(-1);
                result.setMsg("诊断内容不能为空");
                result.setData(false);
                return result;
            }
        }
        return projectService.saveDoc_Survey(docSurveyVO, session);
    }


    @GetMapping("/homePage/index")
    public String homePage(){
        return "homePage/index";
    }
//    统计状态
    @ResponseBody
    @GetMapping("/status/statistics")
    public Map<String, Integer> getProjectStatusStatistics() {
        return projectService.getProjectStatusStatistics();
    }


    @ResponseBody
    @GetMapping("/pretraining/schameVersionInfo")
    public List<SchemaVersionInfoVO> getSchameVersionInfo(@RequestParam(value = "id") Integer projectId) {
        List<SchemaVersionInfoVO> schemaVersionInfoVOList = projectService.getSchameVersionInfo(projectId);
        if (schemaVersionInfoVOList == null || schemaVersionInfoVOList.isEmpty()){
            schemaVersionInfoVOList = new ArrayList<>();
        }

        return schemaVersionInfoVOList;
    }


    @ResponseBody
    @GetMapping("/pretraining/surveyVersionInfo")
    public List<DefaultVersionInfoVO> surveyVersionInfo(@RequestParam(value = "id") Integer projectId, HttpSession session) {
        List<DefaultVersionInfoVO> defaultVersionInfoVOS = projectService.getVersionInfoDefault(projectId, session);
        if (defaultVersionInfoVOS == null || defaultVersionInfoVOS.isEmpty()){
            defaultVersionInfoVOS = new ArrayList<>();
        }

        return defaultVersionInfoVOS;
    }

    @ResponseBody
    @GetMapping("/pretraining/reportVersionInfo")
    public List<ReportVersionInfoVO> reportVersionInfo(@RequestParam(value = "id") Integer projectId) {
        List<ReportVersionInfoVO> reportVersionInfoVOS = projectService.getReportVersionInfo(projectId);
        if (reportVersionInfoVOS == null || reportVersionInfoVOS.isEmpty()){
            reportVersionInfoVOS = new ArrayList<ReportVersionInfoVO>();
        }
        return reportVersionInfoVOS;
    }

    @ResponseBody
    @GetMapping("/pretraining/exportWorldSurveyInfo")
    public void exportWorldSurveyInfo(@RequestParam(value = "version") Long version, HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        String versionStr = String.valueOf(version);
        response.setHeader("Content-Disposition", "attachment;filename=" + versionStr + ".docx");
        try {
            exportService.exportWorldSurveyInfo(version, response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("导出Word失败", e);
        }
    }

    @ResponseBody
    @GetMapping("/pretraining/exportPdfSurveyInfo")
    public void exportPdfSurveyInfo(@RequestParam("version") Long version, HttpServletResponse response) {
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment;filename=SurveyReport.pdf");
        try {
            exportService.exportPdfSurveyInfo(version, response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("导出PDF失败", e);
        }
    }

    @ResponseBody
    @GetMapping("/pretraining/exportPdfSchemaInfo")
    public void exportPdfSchemaInfo(@RequestParam("version") Long version, HttpServletResponse response) {
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment;filename=SurveyReport.pdf");
        try {
            exportService.exportPdfSchemaInfo(version, response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("导出PDF失败", e);
        }
    }

    @ResponseBody
    @GetMapping("/pretraining/exportWorldSchemaInfo")
    public void exportWorldSchemaInfo(@RequestParam(value = "version") Long version, HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        String versionStr = String.valueOf(version);
        response.setHeader("Content-Disposition", "attachment;filename=" + versionStr + ".docx");
        try {
            exportService.exportWorldSchemaInfo(version, response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("导出Word失败", e);
        }
    }

    @ResponseBody
    @GetMapping("/pretraining/exportPdfReportInfo")
    public void exportPdfReportInfo(@RequestParam("version") Long version, HttpServletResponse response) {
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment;filename=SurveyReport.pdf");
        try {
            exportService.exportPdfReportInfo(version, response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("导出PDF失败", e);
        }
    }

    @ResponseBody
    @GetMapping("/pretraining/exportWorldReportInfo")
    public void exportWorldReportInfo(@RequestParam(value = "version") Long version, HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        String versionStr = String.valueOf(version);
        response.setHeader("Content-Disposition", "attachment;filename=" + versionStr + ".docx");
        try {
            exportService.exportWorldReportInfo(version, response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("导出Word失败", e);
        }
    }
}
